package com.zzyl.nursing.service.impl;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.task.vo.IotMsgNotifyData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author szc
 * @date 2025-08-23
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    @Override
    public TableDataInfo<DeviceData> pageQuery(DeviceDataPageReqDto deviceDataPageReqDto) {
        Integer pageNum = deviceDataPageReqDto.getPageNum();
        Integer pageSize = deviceDataPageReqDto.getPageSize();
        LocalDateTime startTime = deviceDataPageReqDto.getStartTime();
        LocalDateTime endTime = deviceDataPageReqDto.getEndTime();
        String deviceName = deviceDataPageReqDto.getDeviceName();
        String functionId = deviceDataPageReqDto.getFunctionId();
        Page<DeviceData> page = new Page<>(pageNum, pageSize);
        this.lambdaQuery().eq(StrUtil.isNotBlank(functionId), DeviceData::getFunctionId, functionId)
                .eq(StrUtil.isNotBlank(deviceName), DeviceData::getDeviceName, deviceName)
                .between(Objects.nonNull(startTime)&&Objects.nonNull(endTime), DeviceData::getAlarmTime, startTime, endTime)
                .orderByDesc(DeviceData::getAlarmTime)
                .page(page);
        TableDataInfo<DeviceData> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 批量插入设备数据
     * @param iotMsgNotifyData
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        // 1.解析上报的数据
        if (Objects.isNull(iotMsgNotifyData)){
            throw new BaseException("数据为空");
        }
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        // 2.通过设备id查询设备
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, deviceId);
        Device device = deviceMapper.selectOne(queryWrapper);
        // 3.设备是否存在
        if(Objects.isNull(device)){
            throw new BaseException("设备不存在");
        }
        // 4.循环构建设备数据
        iotMsgNotifyData.getBody().getServices().forEach(s->{

            //所有数据都已经装入到map中
            Map<String, Object> properties = s.getProperties();
            if (ObjectUtil.isEmpty(properties)){
                return;
            }
            //处理上报时间日期
            LocalDateTime eventTime =  LocalDateTimeUtil.parse(s.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.systemDefault())
                    .toLocalDateTime();

            List<DeviceData> deviceDataList = new ArrayList<>();

            //5.添加到集合中
            properties.forEach((key, value)->{
                DeviceData deviceData = DeviceData.builder()
                        .iotId(deviceId)
                        .deviceName(device.getDeviceName())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(key)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .alarmTime(alarmTime.plusHours(8))
                        .dataValue(value)
                        .build();
                deviceDataList.add(deviceData);
            });
            // 6.批量保存
            saveBatch(deviceDataList);


            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,deviceId,deviceDataList);
        });
    }
}
